package com.sprite.framework.entity.model;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.sprite.framework.entity.EntityException;
import com.sprite.framework.entity.FieldConstancts;
import com.sprite.utils.UtilCollection;


/**
 * 实体
 * @author Jack
 */
public final class ModelEntity implements ModelEntityView{
	private String entityName;
	private String tableName;
	private String entitySingleName;
	private String packageName;
	
	// key is fieldName
	private Map<String, ModelField> fields = new LinkedHashMap<>();
	
	private List<ModelField> keys = new LinkedList<>();
	
	public ModelEntity() {}
	
	public ModelField getModelField(String fieldName) throws EntityException{
		ModelField field = fields.get(fieldName);
		if(field == null){
			throw new EntityException("not find field["+fieldName+"] in entity ["+entityName+"]");
		}
		return field;
	}
	
	public boolean hasField(String fieldName){
		return fields.get(fieldName) != null;
	}
	
	public void setEntityName(String entityName) {
		this.entityName = entityName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public String getEntityName() {
		return entityName;
	}
	
	public String getTableName() {
		return tableName;
	}
	
	public String getEntitySingleName() {
		return entitySingleName;
	}

	public void setEntitySingleName(String entitySingleName) {
		this.entitySingleName = entitySingleName;
	}

	public String getPackageName() {
		return packageName;
	}

	public void setPackageName(String packageName) {
		this.packageName = packageName;
	}

	public List<ModelField> getFields() {
		return new LinkedList<>(fields.values());
	}

	/**
	 * 获取实体主键字段
	 * @return 组件列表
	 */
	public List<ModelField> getKeys() {
		return keys;
	}

	public ModelField getFieldByColumnName(String columnName) {
		for(ModelField modelField : fields.values()) {
			if(modelField.getFieldName().equalsIgnoreCase(columnName)) {
				return modelField;
			}
		}
		
		return null;
	}
	
	public void addModelField(ModelField modelField){
		this.fields.put(modelField.getFieldName(), modelField);
		if(modelField.isKey()) {
			keys.add(modelField);
		}
	}
	
	public void setModelFields(List<ModelField> fields){
		if(fields == null){
			return;
		}
		
		for(ModelField modelField : fields){
			this.fields.put(modelField.getFieldName(), modelField);
		}
	}
	
	public void extend(ModelEntity modelEntity) {
		this.keys.addAll(modelEntity.getKeys());
		this.fields.putAll(modelEntity.fields);
	}
	
	/**
	 * 是否需要逻辑删除
	 * @return 是否逻辑删除
	 */
	public boolean isLogiclyDeletable() {
		return hasField(FieldConstancts.DELETED);
	}

	@Override
	public String resolveFieldPath(String fieldPath) {
		return getModelField(fieldPath).getColName();
	}
}
